package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.pojo.Token;
import com.lagou.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
@Transactional
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public String addToken(String email, String password) {
        Token token = new Token();
        token.setEmail(email);
        token.setPassword(password);
        String uuid = UUID.randomUUID().toString();
        token.setToken(uuid);
        tokenDao.save(token);
        return uuid;
    }

    @Override
    public boolean isRegistered(String email) {
        Token token = new Token();
        token.setEmail(email);
        Example<Token> example = Example.of(token);
        List<Token> tokenList = tokenDao.findAll(example);
        if (tokenList != null && !tokenList.isEmpty()) {
            return true;
        }
        return false;
    }

    @Override
    public Token findToken(String email, String password) {
        Token token = new Token();
        token.setEmail(email);
        token.setPassword(password);
        Example<Token> example = Example.of(token);
        Optional<Token> optionalToken = tokenDao.findOne(example);
        if (optionalToken.isPresent()) {
            return optionalToken.get();
        }
        return null;
    }

    @Override
    public void updateToken(Token token) {
        tokenDao.save(token);
    }

    @Override
    public String findEmail(String uuid) {
        Token token = new Token();
        token.setToken(uuid);
        Example<Token> example = Example.of(token);
        Optional<Token> optionalToken = tokenDao.findOne(example);
        return optionalToken.get().getEmail();
    }
}
